package cshi.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

class Task implements Callable<Integer>{

	@Override
	public Integer call() throws Exception {
		System.out.println("callable thread");
		int sum = 0;
		for (int i=0; i<100; i++)
			sum += i;
		return sum;
	}
	
}

/*
 * public class FutureTask<V> implements RunnableFuture<V>
 * public interface RunnableFuture<V> extends Runnable, Future<V> {
 * void run();
 */


//　如果为了可取消性而使用 Future 但又不提供可用的结果，则可以声明 Future<?> 形式类型、并返回 null 作为底层任务的结果。

public class FutureAndCallable {
	
	public static void test1() throws Exception{
		ExecutorService es = Executors.newCachedThreadPool();
		Task task = new Task();
		Future<Integer> re= es.submit(task);
		System.out.println("result:" + re.get());
		es.shutdown();//very important
	}
	
	public static void useFutureTask() throws Exception {
		Task task = new Task();
		FutureTask<Integer> futureTask = new FutureTask<>(task);
		Thread thread = new Thread(futureTask);
		thread.start();
		
		System.out.println("result:" + futureTask.get());
	}
	
	public static void main(String[] args) throws Exception{
		//test1();
		useFutureTask();
	}

}
